/* 
 * 创建日期 2011-3-30
 *
 * 成都天和软件公司
 * 电话：028-85425861 
 * 传真：028-85425861-8008 
 * 邮编：610041 
 * 地址：成都市武侯区航空路6号丰德万瑞中心B座1001 
 * 版权所有
 */
package  org.fantasy.cpp.core.pool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import  org.fantasy.cpp.core.pojo.SourceInfo;
import  org.fantasy.common.db.QryFactory;
import  org.fantasy.common.db.bean.Row;
import  org.fantasy.common.db.config.Options;
import  org.fantasy.common.db.pool.DBOptions;
import  org.fantasy.common.db.pool.DataSourcePool;

/**
 * 查询工厂池
 * 
 * @author 王文成
 * @version 1.0
 * @since 2011-3-30
 */
public class QryFactoryPool {
	
	private static final Log log = LogFactory.getLog(QryFactoryPool.class);

	/**
	 * 连接池Map
	 */
	private final Map<SourceInfo, QryFactory> poolMap = new HashMap<SourceInfo, QryFactory>();
	
	private Options options;

	public void setOptions(Options options) {
		this.options = options;
	}

	/**
	 * 取得工厂池
	 * 
	 * @param source
	 * @return
	 */
	public QryFactory getQryFactory(SourceInfo source) {
		QryFactory factory = null;
		synchronized (poolMap) {
			if (poolMap.containsKey(source)) {
				factory = poolMap.get(source);
			} else {
				log.info("Create new QryFactory![" + source + "]");
				factory = newQryFactory(source);
				poolMap.put(source, factory);
			}
		}
		return factory;
	}
	
	/**
	 * 创建新的查询工厂
	 * @param options
	 * @return
	 */
	private QryFactory newQryFactory(SourceInfo info){
		try {
			DBOptions dbOptions = info.toDBOptions();
			String className = info.getSourceClass();
			QryFactory qryFactory = (QryFactory)Class.forName(className).newInstance();
			DataSource dataSource = DataSourcePool.getDataSource(dbOptions);
			qryFactory.setDataSource(dataSource);
			qryFactory.setOptions(options);
			return qryFactory;
		} catch (Exception e) {
			log.error(e);
			e.printStackTrace();
			throw new RuntimeException("创建查询工厂失败!");
		}
	}
	
	public static void main(String[] args) throws Exception {
		SourceInfo info = new SourceInfo();
		info.setDriverClass("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		info.setUrl("jdbc:sqlserver://localhost:1433;databaseName=cip");
		info.setUserName("sa");
		info.setPassword("9ol.0p;/");
		info.setSourceClass(" org.fantasy.common.db.sqlserver.SqlServerQryFactory");
		QryFactoryPool pool = new QryFactoryPool();
		pool.setOptions(new Options());
		QryFactory factory = pool.newQryFactory(info);
		List<Row> rows = factory.getQuery("select * from user_info").list();
		System.out.println(rows.get(0));
	}

}
